package com.chenlehao.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
@Slf4j
public class uploadFile {
    // OSS基本配置
    // 配置类注入
    @Autowired
    private aliyunProperties aliyunProperties;

    // 上传图片
    public String upload(MultipartFile file) throws IOException {
        String endpoint = aliyunProperties.getEndpoint();
        String accessKey = aliyunProperties.getAccessKey();
        String accessKeySecret = aliyunProperties.getAccessKeySecret();
        String bucketName = aliyunProperties.getBucketName();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, accessKeySecret);
        // 获取需要上传文件的文件流
        InputStream inputStream = file.getInputStream();

        // 获取唯一文件名
        // 使用uuid字符串
        String uuid = UUID.randomUUID().toString();
        // 新文件名为uuid加上原来的文件名
        String newFileName = uuid + file.getOriginalFilename();

        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, newFileName, inputStream);
        // 创建PutObject请求。
        PutObjectResult result = ossClient.putObject(putObjectRequest);

        // 获取访问url
        String url = "https://" + bucketName + "." + endpoint.split("//")[1] + "/" + newFileName;

        log.info("文件上传到阿里云OSS成功, 访问的路径是{}", url);
        return url;
    }
}
